class Complie {
  constructor(el, vm) {
    this.el = el;
    this.vm = vm;
    // 编译模板
    if (this.el) {
      let fragmeng = this.setFragmeng(this.el);

      this.complie(fragmeng);
      this.el.appendChild(fragmeng);
    }
  }

  /**
   *
   * @param {*} node
   * 将元素添加fragmeng（内存中）
   */
  setFragmeng(node) {
    let nodes = node.childNodes;

    let fragmeng = document.createDocumentFragment();
    this.toArray(nodes).forEach(node => {
      fragmeng.appendChild(node);
    });
    // for (let i = 0; i < nodes.length; i++) {
    //   console.log(nodes[i]);
    //   fragmeng.appendChild(nodes[i]);
    // }
    return fragmeng;
  }
  toArray(likeArray) {
    return [].slice.call(likeArray);
  }
  complie(fragment) {
    let nodes = fragment.childNodes;
    this.toArray(nodes).forEach(node => {
      if (node.nodeType === 1) {
        // 元素节点
        this.elementNodeHandle(node);
      }
      if (node.nodeType === 3) {
        // 文本节点
        this.textNodeHandle(node);
      }
      if (node.childNodes && node.childNodes.length > 0) {
        this.complie(node);
      }
    });
  }
  textNodeHandle(node) {
    let txt = node.textContent;
    let reg = /\{\{(.+)\}\}/;
    if (reg.test(txt)) {
      // RegExp.$1 是一个正则的全局对象的第一个子表达式所匹配的内容
      let value = RegExp.$1;
      node.textContent = node.textContent.replace(reg, this.vm.$data[value]);
    }
  }
  elementNodeHandle(node) {
    let attributes = node.attributes;
    this.toArray(attributes).forEach(item => {
      let name = item.name;
      if (this.isDirective(name)) {
        let type = name.split("v-")[1];
        let value = item.value;
        if (type === "text") {
          node.textContent = this.vm.$data[value];
        }
        if (type === "html") {
          node.innerHTML = this.vm.$data[value];
        }
      }
    });
  }
  isDirective(item) {
    return item.startsWith("v-");
  }
}
